package com.yuw.utils;


import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.lang3.StringUtils;
import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.InvocationTargetException;
import java.util.Enumeration;

public class MyUtils {
    public static <T> T convertReaquest2Bean(HttpServletRequest request, Class<T> tClass) throws IllegalAccessException, InstantiationException, InvocationTargetException {
        T t = null;
        t = tClass.newInstance();
        //转化前端from数据
        Enumeration<String> parameterNames = request.getParameterNames();
        if (parameterNames != null) {
            while (parameterNames.hasMoreElements()) {
                //获取元素
                String strName = parameterNames.nextElement();
                String value = request.getParameter(strName);
                if (StringUtils.isNotEmpty(value)) {
                    //使用反射
                    BeanUtils.setProperty(t, strName, value);
                }
            }
        }
        return t;
    }
    /**
     * 简单工厂：获取一个Class的实例对象 【可以使用Spring框架的IOC 或者 DI 来进行智能处理】
     *
     * @param tClass Class参数
     * @return 实例对象
     */
    public static <T> T getNewInstance(Class<T> tClass) {
        // 默认返回值
        T t = null;
        try {
            t = tClass.newInstance();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
        return t;
    }
}
